﻿using BlazorAdmin.Models;
using BlazorAdmin.Interface;
using BootstrapBlazor.Components;
using BlazorAdmin.Web.Shared.Providers;
using BlazorAdmin.Web.Shared.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Web;
using System.Diagnostics.CodeAnalysis;

namespace BlazorAdmin.Web.Shared.Pages.Account
{
    /// <summary>
    /// 登录组件
    /// </summary>
    public partial class LensLogin
    {
        private const string StringAt = "@";
        private static readonly SelectedItem[] Domains = new SelectedItem[] { new SelectedItem("pangeo.com", "pangeo.com") };

        [CascadingParameter(Name = "AppInfo")]
        public SysInfo? AppInfo { get; set; }

        [CascadingParameter(Name = "ClientInfo")]
        public ClientInfo? ClientInfo { get; set; }

        #region 事件处理
        private async Task OnPasswordEnterAsync(string value) => await OnLoginClickAsync(default);

        private async Task OnLoginClickAsync(MouseEventArgs? e)
        {
            var param = new UserLogin()
            {
                UserName = AppContext.LoginName,
                Password = AppContext.LoginPassword,
                ClientIP = ClientInfo.Ip,
                UserAgent = ClientInfo.UserAgent,
            };

            string domain = AppContext.IsDomain ? AppContext.LoginDomain : string.Empty;
            (JwtUserData userData, User user, string message) = AdminService.Login(param, AppContext.IsRemember, domain);

            if (null == userData || null == user || !string.IsNullOrEmpty(message))
            {
                await MessageService.Show(new MessageOption { Content = message, Color = Color.Danger, });
                return;
            }

            if (AuthProvider is AuthenticationProvider authProvider)
            {
                AppContext.CurrentUser = user;
                authProvider.UpdateToken(userData, AppContext.LoginPassword);
                CascadingValue1 = "2";
            }
        }
        #endregion

        #region Inject

        [Inject]
        [NotNull]
        private IBootstrapAdminService? AdminService { get; set; }

        [Inject]
        [NotNull]
        private MessageService? MessageService { get; set; }

        [Inject]
        [NotNull]
        private BootstrapAppContext? AppContext { get; set; }

        [Inject]
        [NotNull]
        private AuthenticationStateProvider? AuthProvider { get; set; }

        [CascadingParameter(Name = nameof(CascadingValue1))]
        private string? CascadingValue1 { get; set; }

        #endregion
    }
}
